package com.example.recyclerview

import android.content.DialogInterface
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import java.util.*
import kotlin.collections.ArrayList

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val recyclerView = findViewById<RecyclerView>(R.id.id_recyclerview)
//        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.layoutManager =
            StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL)
        recyclerView.itemAnimator = DefaultItemAnimator()
        val homeAdapter = HomeAdapter(makeData(), makeHeight(), this)
//        recyclerView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST))
        recyclerView.adapter = homeAdapter
        homeAdapter.setOnItemClickListener(object : OnItemClickListener {
            override fun onItemClick(view: View, position: Int) {
                val textView = view as TextView
                val text = textView.text
                Toast.makeText(this@MainActivity,
                    "点击第$text 条", Toast.LENGTH_SHORT).show()
            }

            override fun onItemLongClick(view: View, position: Int) {
                AlertDialog.Builder(this@MainActivity)
                    .setTitle("确定要删除吗?")
                    .setNegativeButton("取消", null)
                    .setNegativeButton("确定") { _, _ -> homeAdapter.removeData(position) }
                    .show()
            }
        })
    }

    private fun makeData(): MutableList<String> {
        val strList = ArrayList<String>()
        for (i in 1..500) {
            strList.add("$i")
        }
        return strList
    }

    private fun makeHeight(): MutableList<Int> {
        val heightList = ArrayList<Int>()
        val random = Random()
        for (i in 1..500) {
            heightList.add(random.nextInt(400))
        }
        return heightList
    }

}
